package com.fanrui.code.dao;

import org.apache.ibatis.session.SqlSession;

import com.fanrui.code.entity.User;
import com.fanrui.code.entity.UserMapper;
import com.fanrui.code.util.SessionUtil;

public class UserDao {
	
	// singleton
	private UserDao() {}
	
	private static class UserDaoSingleton {
		private static UserDao instance = new UserDao();
	}
	
	public static UserDao getInstance() {
		return UserDaoSingleton.instance;
	}
	
	/**
	 * 根据账号查询用户
	 * @param account
	 * @return
	 */
	public User findUserByAccount(String account) {
		try(SqlSession session = SessionUtil.getSession()) {
			UserMapper mapper = session.getMapper(UserMapper.class);
			return mapper.selectByAccount(account);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void save(User user) {
		try (SqlSession session = SessionUtil.getSession()) {
			UserMapper um = session.getMapper(UserMapper.class);
			um.updateByPrimaryKey(user);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 创建一个user
	 * @param user
	 * @return
	 */
	public User createUser(User user) {
		try (SqlSession session = SessionUtil.getSession()) {
			UserMapper um = session.getMapper(UserMapper.class);
			if(um.selectByAccount(user.getAccount()) != null){
				return null;
			}else{
				int result = um.insertSelective(user);
				if (result == 1) {
					session.commit();
					return user;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public User findUserById(Long id) {
		try(SqlSession session = SessionUtil.getSession()) {
			UserMapper mapper = session.getMapper(UserMapper.class);
			return mapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
